import functools
import json

from flask import (
    Blueprint, flash, g, redirect, render_template, request, session, url_for,jsonify,Response,abort
)
from werkzeug.security import check_password_hash, generate_password_hash

from flaskr.db import get_db

from flask_cors import *

bp = Blueprint('account', __name__, url_prefix='/')

cors=CORS(bp,supports_credentials=True)

@bp.route('/account', methods=['GET','POST','DELETE'])
def account_manage():
    if request.method == 'GET':
        # data = request.args
        if(session.get('permission') != 'Root'):
            abort(403)
        db = get_db()
        account_list = db.execute(
            'SELECT id,username,nucleic_acid,vaccine,phone,address,create_time FROM Medical_point'
        ).fetchall()
        list = []
        for record in account_list:
            list.append({'id':record['id'],'username':record['username'],
            'nucleic_acid':record['nucleic_acid'],'vaccine':record['vaccine'],
            'phone':record['phone'],'address':record['address'], 'create_time':record['create_time']})
        return jsonify({'account_list':list})
    elif request.method == 'POST':
        if(session.get('permission') != 'Root'):
            abort(403)
        data = request.get_data()    
        data = json.loads(data.decode("utf-8"))
        username = data['username']
        password = data['password']
        address = data['address']
        phone = data['phone']
        create_time = data['create_time']
        db = get_db()
        user = db.execute(
            'SELECT username FROM Medical_point WHERE username = ?', (username,)
            ).fetchone()
        if user is not None:
            res = Response(f"用户名 {username} 已被注册")
            abort(res)
        try:
            db.execute(
                "INSERT INTO Medical_point (username, password, nucleic_acid, vaccine, address, phone, create_time) VALUES (?, ?, 0, 0, ?, ?, ?)",
                (username, generate_password_hash(password), address, phone, create_time,),
            )
            db.commit()
        except db.IntegrityError:
            abort(500)
            # res = Response(f"手机号 {phone} 已被注册")
            # abort(res)
        else:
            return 'success'
    elif request.method == 'DELETE':
        if(session.get('permission') != 'Root'):
            abort(403)
        data = request.get_data()    
        data = json.loads(data.decode("utf-8"))
        username = data['username']
        db = get_db()
        try:
            db.execute(
                "DELETE FROM Medical_point WHERE username = ?",
                (username,),
            )
            db.commit()
        except db.IntegrityError:
            abort(500)
        else:
            return 'success'
    abort(405)